package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.NewSocietyOrganizationAdapter;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.NewSocietyOrganizationBean;
import com.sx.zongzhi.bean.OrganizingBean;
import com.sx.zongzhi.bean.SocietyOrganizionBean;
import com.sx.zongzhi.bean.UserBean;
import com.sx.zongzhi.bean.UserPermission;
import com.sx.zongzhi.presenter.NewSocietyOrganizationPest;
import com.sx.zongzhi.utils.AppConstants;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.INewSocietyOrganizationView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**新社会组织
 * Created by admin on 2017/12/8.
 */

public class NewSocietyOrganizationActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, INewSocietyOrganizationView {
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.imvAdd)
    ImageView imvAdd;
    @BindView(R.id.tv_Total)
    TextView tvTotal;

    private NewSocietyOrganizationAdapter adapter;
    private List<NewSocietyOrganizationBean> beanList = new ArrayList<>();

    private int page = 1, rows = 10, haveOverSea = 0;
    private String name = "",  typeId = "",  address = "",  legalPerson = "",
            legalSafePerson = "",  legalPersonTelephone = "", legalPersonMobileNumber = "",
            legalSafePersonTelephone = "", legalSafePersonMobileNumber = "",  registrationManagementCode = "",
            moneySource = "", registrationNumber = "", unifiedSocialCreditCode = "", orgId = "";
    private Disposable disposable;

    private UserPermission userPermission;
    private boolean isCurrentGrid = false;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_household);
        setTitleName(R.string.newSocietyOrganization);
        ButterKnife.bind(this);
        setRightImage(R.mipmap.icon_nav_search);
        initView();
    }
    private void initView() {
        IDataStorage dataStorage= DataStorageFactory.getInstance(
                getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        UserBean userBean = dataStorage.load(UserBean.class,getPackageName());
        orgId = userBean.getOrg().getId();
        imvAdd.setVisibility(View.GONE);
        if ("片组片格".equals(userBean.getOrg().getOrgLevel().getDisplayName())){
            isCurrentGrid = true;
        }else {
            setRightImage2(R.mipmap.icon_nav_position);
        }
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(AppConstants.colors);
            swipeRefreshLayout.setOnRefreshListener(this);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new NewSocietyOrganizationAdapter(this, R.layout.item_social_list, beanList);
        adapter.setEmptyView(View.inflate(this, R.layout.load_error_view, null));
        recyclerView.setAdapter(adapter);
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                getData();
            }
        }, recyclerView);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(NewSocietyOrganizationActivity.this, NewSocietyOrganizationDetailActivity.class)
                        .putExtra("id", beanList.get(position).getId())
                .putExtra("userPermission",userPermission));
            }
        });
        initRx();
        onRefresh();
    }
    private void initRx() {
        disposable = MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent bean) throws Exception {
                        if (bean.getRequest().equals("NewSocietyOrganizationActivity")){
                            if (bean.getType() == 0){
                                OrganizingBean oBean = (OrganizingBean) bean.getMsg();
                                if (oBean != null) {
                                    orgId = oBean.getId();
                                    if (oBean.isGrid() && userPermission != null && userPermission.isAddNewSocietyOrganizations()){
                                        imvAdd.setVisibility(View.VISIBLE);
                                    }else {
                                        imvAdd.setVisibility(View.GONE);
                                    }
                                }
                                page = 1;
                                getData();
                            }else if (bean.getType() == 2){
                                SocietyOrganizionBean beans = (SocietyOrganizionBean) bean.getMsg();
                                name = beans.name;
                                typeId = beans.typeId;
                                registrationNumber = beans.registrationNumber;
                                registrationManagementCode = beans.registrationManagementCode;
                                unifiedSocialCreditCode = beans.unifiedSocialCreditCode;
                                legalPerson = beans.legalPerson;
                                legalPersonTelephone = beans.legalPersonTelephone;
                                legalPersonMobileNumber = beans.legalPersonMobileNumber;

                                legalSafePerson = beans.legalSafePerson;
                                legalSafePersonTelephone = beans.legalSafePersonTelephone;
                                legalSafePersonMobileNumber = beans.legalSafePersonMobileNumber;

                                moneySource = beans.moneySource;
                                haveOverSea = beans.haveOverSea;
                                page = 1;
                                getData();
                            }else if (bean.getType() != 0 && bean.getType() != 2){
                                onRefresh();
                            }
                        }
                    }
                });
    }

    @OnClick({R.id.imv_Right, R.id.imv_Right2, R.id.imvAdd})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.imv_Right:
                startActivity(new Intent(NewSocietyOrganizationActivity.this, NewSocietyOrganizationSearchActivity.class));
                break;
            case R.id.imv_Right2:
                startActivity(new Intent(this, OrganizingActivity.class).
                        putExtra(Global.ACTIVITY_FRAGMENT, "NewSocietyOrganizationActivity"));
                break;
            case R.id.imvAdd:
                startActivity(new Intent(NewSocietyOrganizationActivity.this, AddNewSocietyOrganizationActivity.class)
                        .putExtra("orgId",orgId));
                break;

        }
    }
    @Override
    public void onRefresh() {
        swipeRefreshLayout.setRefreshing(false);
        page = 1;
        getData();
    }
    private void getData() {
        new NewSocietyOrganizationPest(this).getNewSocietyOrganizationList(this, page, rows,
                name,typeId,address,legalPerson,legalSafePerson,legalPersonTelephone,
                legalPersonMobileNumber,legalSafePersonTelephone,legalSafePersonMobileNumber
                ,registrationManagementCode,moneySource,registrationNumber,unifiedSocialCreditCode,haveOverSea,orgId);
    }

    @Override
    public void showError(String message) {
        ToastUtils.showToast(NewSocietyOrganizationActivity.this,message);
    }

    @Override
    public void getNewSocietyOrganizationListSuccess(UserPermission userPermissions, List<NewSocietyOrganizationBean> list, int total) {
        if (userPermissions != null && userPermission == null){
            userPermission = userPermissions;
            if (isCurrentGrid && userPermission.isAddNewSocietyOrganizations()){
                imvAdd.setVisibility(View.VISIBLE);
            }
        }
        if (page == 1) {
            beanList.clear();
            adapter.setNewData(beanList);
        }
        if (list != null && list.size() > 0) {
            beanList.addAll(list);
        }
        adapter.notifyDataSetChanged();
        tvTotal.setText( "共"+total + "条数据");
        if (beanList.size() == total) {
            adapter.loadMoreEnd();
        }else {
            adapter.loadMoreComplete();
        }
    }
    @Override
    protected void onDestroy() {
        if (disposable != null){
            disposable.dispose();
        }
        beanList = null;
        super.onDestroy();
    }
}
